﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Xml;
using System.Xml.Linq;

namespace LightingServer.TCP.Start
{
    class Program
    {
        static Program()
        {
            try
            {
                Type interfaceType = typeof(IServerCommand);

                foreach (Type type in Assembly.GetExecutingAssembly().GetTypes())
                {
                    Type[] interfaces = type.GetInterfaces();
                    if (interfaces != null && interfaces.Contains(interfaceType))
                    {
                        Registrar.Register((IServerCommand)Activator.CreateInstance(type));
                    }
                }
            }
            catch (Exception ex)
            {
            }
        }

        static void Main(string[] args)
        {

            LightingServerContext.ConnectionStrings = GetConnectionStrings();
            ReadConfig();

            Registrar.TCPListenPort = 4530;
            Registrar.TCPReceiveBufferSize = 65536;
            Registrar.TCPSendBufferSize = 65536;
            TCPServer tcpServer = new TCPServer();
            tcpServer.Start();
            Console.Read();
        }

        private static string GetConnectionStrings()
        {
            string server = "localhost";
            string database = "zcdb";
            string uid = "root";
            string password = "";
            return "SERVER=" + server + ";" + "DATABASE=" + database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";";
        }

        private static void ReadConfig()
        {
            string configPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "ServerConfig.xml");
            XDocument doc = XDocument.Load(configPath);
            LightingServerContext.ImageRoot = doc.Root.Element("ImageRoot").Value;
            LightingServerContext.ImageUrl =  doc.Root.Element("ImageUrl").Value;
            LightingServerContext.TemplateRoot =  doc.Root.Element("TemplateRoot").Value;
            LightingServerContext.ExportRoot = doc.Root.Element("ExportRoot").Value;
            LightingServerContext.ExportUrl = doc.Root.Element("ExportUrl").Value;
            LightingServerContext.Database = doc.Root.Element("Database").Value;
            LightingServerContext.CacheUrl = doc.Root.Element("Cache").Value;

            int expiry = 0;
            if (int.TryParse(doc.Root.Element("Expiry").Value, out expiry))
                LightingServerContext.Expiry = TimeSpan.FromHours(expiry).TotalMilliseconds;
        }
    }
}
